package com.xy.smartsms.service.carrierparam;

import android.content.Context;
import android.text.TextUtils;

import com.xy.smartsms.db.carrierparam.OnlineConfigManager;
import com.xy.smartsms.db.carrierparam.WhiteListManager;
import com.xy.smartsms.db.carrierparam.entity.OnlineConfigItem;
import com.xy.smartsms.db.carrierparam.entity.WhiteListItem;
import com.xy.smartsms.constant.NetConstant;
import com.xy.smartsms.util.Log;
import com.xy.smartsms.util.ThreadManager;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import cn.com.xy.sms.sdk.Iservice.XyCallBack;
import cn.com.xy.sms.sdk.db.entity.SysParamEntityManager;
import cn.com.xy.sms.sdk.iccid.IccidLocationUtil;
import cn.com.xy.sms.sdk.util.BaseRunnable;

/**
 * Created by kangwenbo on 2017/3/1.
 */

public class UpdateWhiteListRunnable extends BaseRunnable {
    private final String TAG = "UpdateSDKSetting";
    private Context mContext;
    private Map<String, Object> queryMap;
    private String mCNum;
    private String mIccid;

    /**
     * @param cNum
     * @param iccid   可以用 IccidLocationUtil.getICCID() 获取
     * @return
     */
    public void requestData(Context context, String cNum, String iccid) {
        mContext = context;
        mCNum = cNum;
        mIccid = iccid;
        ThreadManager.executeRunnableByPool(ThreadManager.NUMBER_UPDATE_CARRIER, this);
    }

    @Override
    protected boolean inQueryInterval() {
        if (OnlineConfigManager.getInstance().getIntervalTime(OnlineConfigItem.FLAG_WHITE_LIST_LAST_VERSION) < System.currentTimeMillis())
            return false;
        return true;
    }

    private void initData() {
        String version = SysParamEntityManager.getStringParam(mContext, WhiteListManager.LOCAL_WHITELIST_VERSION);
        if (TextUtils.isEmpty(version))
            version = "201703191011";
        queryMap = new HashMap<String, Object>();
        queryMap.put("version", version);
        queryMap.put("iccid", mIccid);
        queryMap.put("operator", IccidLocationUtil.getOperatorNameByICCID(mIccid));
        queryMap.put("cNum", mCNum);
    }

    @Override
    public void execute() {
        initData();
        UpdateCarrierParamService.updateDataByNet(NetConstant.REQUEST_URL_OWN_NUMBER, queryMap, new HashMap<String, String>(), new XyCallBack() {
            @Override
            public void execute(Object... objects) {
                try {
                    JSONObject jb = UpdateCarrierParamService.isValidOfData(objects);
                    if (jb == null) {
                        UpdateCarrierParamService.updateOnlineConfig(OnlineConfigItem.FLAG_WHITE_LIST_LAST_VERSION, OnlineConfigItem.STATUS_FAIL);
                        return;
                    }
                    analysisData(jb);
                    UpdateCarrierParamService.updateOnlineConfig(OnlineConfigItem.FLAG_WHITE_LIST_LAST_VERSION, OnlineConfigItem.STATUS_SUCCESS);

                    if ("90004".equals(jb.optString("code"))) {
                        //Continue to getData
                        getMoreData();
                    }else{
                        WhiteListManager.getInstance().refreshSectionNo();
                    }
                } catch (Throwable t) {
                    Log.e(TAG, "execute", t);
                    UpdateCarrierParamService.updateOnlineConfig(OnlineConfigItem.FLAG_WHITE_LIST_LAST_VERSION, OnlineConfigItem.STATUS_FAIL);
                }
            }
        });
    }

    private void getMoreData(){
        execute();
    }

    private void analysisData(JSONObject jsonObject) {
        try {
            if (jsonObject.has("datas")) {
                JSONArray jsonArray = jsonObject.optJSONArray("datas");
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jb = jsonArray.optJSONObject(i);
                    WhiteListItem item = new WhiteListItem();
                    item.setNumber(jb.optString("number").trim());
                    int status = jb.optInt("status");
                    if (status == -1) {
                        //delete
                        WhiteListManager.getInstance().delete(item);
                    } else {
                        //update or insert
//                        item.setLevel(WhiteListItem.LEVEL_HIGH);
                        item.setLevel(jb.optInt("whiteType"));
                        item.setName(jb.optString("pubName"));
                        item.setExtendVal(jb.optString("extendVal"));
                        if(item.getNumber().endsWith("*")){
                            item.setIsSectionNo(WhiteListItem.YES);
                            if(jb.has("maxlen") || jb.has("minlen")){
                                item.setMaxLen(jb.optInt("maxlen"));
                                item.setMinLen(jb.optInt("minlen"));
                                item.setLen(-1);
                            }else{
                                item.setMaxLen(-1);
                                item.setMinLen(-1);
                                item.setLen(jb.optInt("len"));
                            }
                        }
                        WhiteListManager.getInstance().updateOrInsert(item);
                    }
                }
                String version = jsonObject.optString("version");
                //// TODO: 2017/3/1 对数据集合的处理
                SysParamEntityManager.setParam(WhiteListManager.LOCAL_WHITELIST_VERSION, version);
            } else {
                Log.i(TAG, jsonObject.getString("content"));
            }
        } catch (Throwable t) {
            Log.e(TAG, "analysisData", t);
        }

    }
}
